package com.huang.binarySearch;

import java.util.Scanner;

public class BSearch {
    static int[] binarySearch(int[] nums, int target) {
        int[] info = new int[2];
        int left = 0;
        int right = nums.length - 1; // 注意

        while (left <= right) { // 注意
            int mid = (right + left) / 2;
            if (nums[mid] == target) {
                info[0] = mid;
                info[1] = mid;
                return info;
            } else if (nums[mid] < target) {
                left = mid + 1; // 注意
                info[0] = mid;
                info[1] = left;
            } else if (nums[mid] > target) {
                right = mid - 1; // 注意
                info[1] = mid;
                info[0] = right;
            }
        }
        return info;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 7, 9, 11, 13, 15};
        System.out.print("存在数组nums=[");
        for (int num : nums) {
            System.out.print(num+" ");
        }
        System.out.println("]");
        Scanner scanner = new Scanner(System.in);
        //输入要查找的数
        System.out.println("输入要查找的数");
        int i = scanner.nextInt();
        int[] info = BSearch.binarySearch(nums, i);
        //确定区间
        System.out.print(i+"所在位置区间[");
        for (int n : info) {
            System.out.print(n+" ");
        }
        System.out.print("]");

    }
}
